package com.mybatisflex.core.util;

import com.mybatisflex.core.exception.MybatisFlexException;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Bean工具类
 *
 * @author zhang
 */
public class BeanUtil {

    /**
     * 缓存字段
     * key: 类名#属性名
     */
    private static final Map<String, Field> FIELD_MAP = new ConcurrentHashMap<>(256);

    /**
     * 设置属性值
     *
     * @param entity    实体类
     * @param fieldName 属性名
     * @param value     属性值
     */
    public static void setProperty(Object entity, String fieldName, Object value) {
        String key = entity.getClass().getName() + "#" + fieldName;
        Field field = FIELD_MAP.get(key);
        if (field == null) {
            field = ClassUtil.getFirstField(entity.getClass(), f -> f.getName().equals(fieldName));
        }
        if (field == null) {
            throw new MybatisFlexException(String.format("无法找到属性[%s]对应的字段。", key));
        }
        FIELD_MAP.put(key, field);
        try {
            field.setAccessible(true);
            field.set(entity, value);
        } catch (IllegalAccessException e) {
            throw new MybatisFlexException(e);
        }
    }
}
